<template>
	<view class="marketing-management" @tap="handlePageClick" :style="themeContainerStyle">
		<!-- 顶部导航栏 -->
		<nav-bar title="营销策略" :show-back="false" />



		<!-- 分类导航 -->
		<view class="category-section">
			<view class="section-header">
				<text class="section-icon">📂</text>
				<text class="section-title">分类筛选</text>
			</view>
			<scroll-view scroll-x="true" class="category-scroll" show-scrollbar="false">
				<view class="category-list">
					<view v-for="category in categories" :key="category" class="category-item"
						:class="{ active: activeCategory === category }" @tap="switchCategory(category)">
						<text class="category-name">{{ category }}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 内容滚动区域 -->
		<scroll-view scroll-y class="content-scroll">
			<!-- 策略列表 -->
			<view class="strategy-section">
				<view class="section-header" v-if="strategiesData && strategiesData.length > 0">
					<text class="section-icon">🎯</text>
					<text class="section-title">推荐策略</text>
					<text class="section-count">{{ strategiesData.length }}个</text>
				</view>

				<view class="strategy-list" v-if="strategiesData && strategiesData.length > 0">
					<view v-for="strategy in strategiesData" :key="strategy.id" class="strategy-card"
						@tap="handleViewDetail(strategy)">
						<!-- 策略媒体 -->
						<view class="strategy-media">
							<image v-if="strategy.mediaType === 'image'" :src="strategy.mediaUrl" mode="aspectFill"
								class="media-image"></image>
							<video v-else-if="strategy.mediaType === 'video'" :src="strategy.mediaUrl"
								:poster="strategy.poster" controls class="media-video"
								@click.stop="handleVideoClick(strategy)"></video>

							<!-- 操作菜单按钮 -->
							<view class="media-menu" @tap.stop>
								<view class="menu-trigger" @tap.stop="toggleMenu(strategy.id)">
									<text class="menu-icon">⋯</text>
								</view>
								<!-- 操作菜单 -->
								<view v-if="activeMenuId === strategy.id" class="action-menu" @tap.stop>
									<view class="action-item" @click="handleEditStrategy(strategy)">
										<text class="action-icon">✏️</text>
										<text class="action-text">编辑</text>
									</view>
									<view class="action-item delete" @click="handleDeleteStrategy(strategy.id)">
										<text class="action-icon">🗑️</text>
										<text class="action-text">删除</text>
									</view>
								</view>
							</view>
						</view>

						<!-- 策略内容 -->
						<view class="strategy-info">
							<text class="strategy-title">{{ strategy.title }}</text>
							<text class="strategy-description">{{ strategy.description }}</text>
							<view class="strategy-footer">
								<view class="strategy-tag">
									<text>{{ activeCategory }}</text>
								</view>
								<view class="strategy-action">
									<text class="action-link">查看详情 →</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-else>
					<view class="empty-animation">
						<text class="empty-icon">🎨</text>
					</view>
					<text class="empty-title">还没有营销策略</text>
					<text class="empty-desc">快来创建你的第一个营销策略吧</text>
					<button class="empty-btn" @click="handleAddStrategy">
						<text class="btn-icon">✨</text>
						<text class="btn-text">立即创建</text>
					</button>
				</view>
			</view>
		</scroll-view>

		<!-- 加载状态 -->
		<view class="loading-overlay" v-if="isLoading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 悬浮新增按钮 -->
		<view class="fab-button" @click="handleAddStrategy">
			<text class="fab-icon">➕</text>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
	import { onShow } from '@dcloudio/uni-app';
	import { OperationStrategy } from '@/types/marketing';
	import { getCategories, getStrategiesByCategory, deleteStrategy } from '@/services/marketing';
	import { baseURL } from '@/utils/config';
	import NavBar from '@/components/nav-bar.vue';
	import { showToast, showLoading, hideLoading, getSafeAreaTop, navigateTo } from '@/utils/global';
	import { getThemeStyles } from '@/stores/theme';
	// 响应式数据
	const isLoading = ref<boolean>(false);
	const categories = ref<string[]>([]);

	const activeCategory = ref<string>('');
	const strategiesData = ref<OperationStrategy[]>([]);
	const scrollTop = ref<number>(0);
	const activeMenuId = ref<number | null>(null);


	// 初始化数据
	const initData = async () => {
		try {
			isLoading.value = true;

			// 获取分类列表
			const categoriesData = await getCategories();
			categories.value = categoriesData.data;

			// 初始化第一个分类的策略数据
			if (categoriesData.data && categoriesData.data.length > 0) {
				activeCategory.value = categoriesData.data[0];
				await fetchStrategiesByCategory(categoriesData.data[0]);
			}
		} catch (error) {
			console.error('加载失败:', error);
			showToast('加载失败，请重试');
		} finally {
			isLoading.value = false;
		}
	};

	// 根据分类获取策略数据
	const fetchStrategiesByCategory = async (category : string) => {
		try {
			const strategies = await getStrategiesByCategory(category);
			// 数据循环处理，如果路径包含：/admin/sys-file/upms，那么添加前缀baseURL
			const processedStrategies = (strategies.data || []).map(item => {
				return {
					...item,
					mediaUrl: baseURL + item.mediaUrl
				};
			});
			strategiesData.value = processedStrategies;

		} catch (error) {
			console.error('获取策略数据失败:', error);
			strategiesData.value = [];
		}
	};

	// 切换分类
	const switchCategory = async (categoryId : string) => {
		if (categoryId) {
			activeCategory.value = categoryId;
			scrollTop.value = 0; // 重置滚动位置
			await fetchStrategiesByCategory(categoryId);
		}
	};




	// 当页面重新显示时（比如从新增/编辑返回），自动刷新当前类目的策略数据
	onShow(() => {
		console.log("页面重新显示", activeCategory.value);
		if (activeCategory.value) {
			fetchStrategiesByCategory(activeCategory.value);
		} else {
			initData();
		}
	});

	// 处理添加策略 - 跳转到编辑页面
	const handleAddStrategy = () => {
		navigateTo('/pages/marketing/edit');
	};

	// 处理查看策略详情
	const handleViewDetail = (strategy : OperationStrategy) => {
		navigateTo(`/pages/marketing/detail?strategyId=${strategy.id}`);
	};

	// 处理视频点击事件
	const handleVideoClick = (strategy : OperationStrategy) => {
		// 视频点击时也跳转到详情页面
		console.log("视频点击", strategy);
	};

	// 切换菜单显示/隐藏
	const toggleMenu = (strategyId : number) => {
		if (activeMenuId.value == strategyId) {
			activeMenuId.value = null;
		} else {
			activeMenuId.value = strategyId;
		}
	};

	// 处理编辑策略 - 跳转到编辑页面
	const handleEditStrategy = (strategy : OperationStrategy) => {
		activeMenuId.value = null; // 关闭菜单
		navigateTo(`/pages/marketing/edit?strategyId=${strategy.id}`);
	};

	// 处理删除策略
	const handleDeleteStrategy = (strategyId : number) => {
		activeMenuId.value = null; // 关闭菜单
		uni.showModal({
			title: '确认删除',
			content: '确定要删除该策略吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						isLoading.value = true;
						await deleteStrategy(strategyId);

						// 更新本地数据
						strategiesData.value = strategiesData.value.filter(s => s.id !== strategyId);

						showToast('删除成功');
					} catch (error) {
						console.error('删除策略失败:', error);
						showToast('删除失败');
					} finally {
						isLoading.value = false;
					}
				}
			}
		});
	};


	// 点击外部关闭菜单
	const handlePageClick = () => {
		activeMenuId.value = null;
	};

	// 获取主题样式
	const themeStyles = computed(() => getThemeStyles());
	
	// 容器主题样式
	const themeContainerStyle = computed(() => ({
		background: themeStyles.value.bgGradient
	}));

	// 页面加载时初始化数据
	onMounted(() => {
		initData();
	});

</script>

<style scoped lang="scss">
	/* 页面容器 */
	.marketing-management {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		/* background 由 themeContainerStyle 动态设置 */
		overflow: hidden;

		/* 内容滚动区域 */
		.content-scroll {
			flex: 1;
			width: 100%;
			height: 0;
		}

		/* 分类区域 */
		.category-section {
			background: #ffffff;
			padding: 32rpx 0 24rpx;
			margin-bottom: 16rpx;
			position: sticky;
			top: 0;
			z-index: 10;
			box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.08);
			border: 1px solid rgba(102, 126, 234, 0.05);

			/* 区域标题 */
			.section-header {
				display: flex;
				align-items: center;
				padding: 0 32rpx 20rpx;
				gap: 12rpx;

				.section-icon {
					font-size: 36rpx;
				}

				.section-title {
					font-size: 32rpx;
					font-weight: 700;
					color: #1e293b;
					flex: 1;
					letter-spacing: 0.5rpx;
				}

				.section-count {
					font-size: 24rpx;
					color: #94a3b8;
					background: #f1f5f9;
					padding: 8rpx 16rpx;
					border-radius: 20rpx;
				}
			}

			.category-scroll {
				width: 100%;
				white-space: nowrap;

				.category-list {
					display: flex;
					padding: 0 32rpx;
					gap: 16rpx;

					.category-item {
						padding: 16rpx 32rpx;
						background: v-bind('themeStyles.bgCard');
						border-radius: 50rpx;
						border: 2rpx solid v-bind('themeStyles.borderLight');
						transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
						white-space: nowrap;
						flex-shrink: 0;

						&.active {
							background: v-bind('themeStyles.primaryGradient');
							border-color: transparent;
							transform: scale(1.05);
							box-shadow: v-bind('themeStyles.activeShadow');

							.category-name {
								color: #ffffff;
							}
						}

						.category-name {
							font-size: 28rpx;
							color: v-bind('themeStyles.textTertiary');
							font-weight: 600;
							transition: color 0.3s cubic-bezier(0.4, 0, 0.2, 1);
						}
					}
				}
			}
		}

		/* 策略区域 */
		.strategy-section {
			padding: 24rpx 0;

			.section-header {
				display: flex;
				align-items: center;
				padding: 0 32rpx 20rpx;
				gap: 12rpx;

				.section-icon {
					font-size: 36rpx;
				}

				.section-title {
					font-size: 32rpx;
					font-weight: 700;
					color: v-bind('themeStyles.textPrimary');
					flex: 1;
					letter-spacing: 0.5rpx;
				}

				.section-count {
					font-size: 24rpx;
					color: v-bind('themeStyles.primaryColor');
					background: v-bind('themeStyles.bgSecondary');
					padding: 8rpx 16rpx;
					border-radius: 20rpx;
				}
			}

			/* 策略列表 */
			.strategy-list {
				display: flex;
				flex-direction: column;
				gap: 20rpx;
				padding: 0 24rpx 120rpx;

				.strategy-card {
					background: v-bind('themeStyles.bgCard');
					border-radius: 24rpx;
					overflow: hidden;
					box-shadow: v-bind('themeStyles.cardBoxShadow');
					transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
					border: v-bind('themeStyles.cardBorder');

					&:active {
						transform: scale(0.98);
						box-shadow: v-bind('themeStyles.hoverBoxShadow');
					}

					/* 策略媒体 */
					.strategy-media {
						width: 100%;
						height: 400rpx;
						position: relative;
						overflow: hidden;
						background: linear-gradient(135deg, #f8fafc 0%, #e9ecef 100%);

						.media-image,
						.media-video {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}

						/* 媒体菜单 */
						.media-menu {
							position: absolute;
							top: 20rpx;
							right: 20rpx;
							z-index: 10;

							/* 菜单触发器 */
							.menu-trigger {
								display: flex;
								align-items: center;
								justify-content: center;
								width: 56rpx;
								height: 56rpx;
								border-radius: 50%;
								background: rgba(0, 0, 0, 0.5);
								backdrop-filter: blur(20rpx);
								transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

								&:active {
									transform: scale(0.9);
									background: rgba(0, 0, 0, 0.7);
								}

								.menu-icon {
									font-size: 32rpx;
									color: #ffffff;
									font-weight: bold;
									line-height: 1;
								}
							}

							/* 操作菜单 */
							.action-menu {
								position: absolute;
								top: 68rpx;
								right: 0;
								background: #ffffff;
								border-radius: 16rpx;
								box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.2);
								overflow: hidden;
								z-index: 100;
								animation: slideDown 0.2s cubic-bezier(0.4, 0, 0.2, 1);

								.action-item {
									display: flex;
									align-items: center;
									gap: 12rpx;
									padding: 24rpx 32rpx;
									background: #ffffff;
									border-bottom: 1rpx solid #f1f5f9;
									transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
									min-width: 160rpx;

									&:last-child {
										border-bottom: none;
									}

									&:active {
										background: #f8fafc;
									}

									&.delete {
										&:active {
											background: #fef2f2;
										}

										.action-text {
											color: #ef4444;
										}
									}

									.action-icon {
										font-size: 32rpx;
									}

									.action-text {
										font-size: 28rpx;
										color: #1e293b;
										font-weight: 600;
									}
								}
							}
						}
					}

					/* 策略信息 */
					.strategy-info {
						padding: 28rpx;
						display: flex;
						flex-direction: column;
						gap: 12rpx;

						.strategy-title {
							font-size: 34rpx;
							font-weight: 700;
							color: v-bind('themeStyles.textPrimary');
							line-height: 1.4;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							-webkit-box-orient: vertical;
							overflow: hidden;
						}

						.strategy-description {
							font-size: 26rpx;
							color: v-bind('themeStyles.textTertiary');
							line-height: 1.6;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							-webkit-box-orient: vertical;
							overflow: hidden;
						}

						.strategy-footer {
							display: flex;
							align-items: center;
							justify-content: space-between;
							margin-top: 8rpx;

							.strategy-tag {
								padding: 8rpx 16rpx;
								background: v-bind('themeStyles.bgSecondary');
								border-radius: 20rpx;
								font-size: 22rpx;
								color: v-bind('themeStyles.primaryColor');
								font-weight: 600;
							}

							.strategy-action {
								.action-link {
									font-size: 24rpx;
									color: v-bind('themeStyles.primaryColor');
									font-weight: 600;
								}
							}
						}
					}
				}
			}

			/* 空状态 */
			.empty-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 120rpx 40rpx;
				text-align: center;

				.empty-animation {
					animation: float 3s ease-in-out infinite;

					.empty-icon {
						font-size: 160rpx;
						margin-bottom: 32rpx;
						filter: grayscale(0.3);
					}
				}

				.empty-title {
					font-size: 36rpx;
					font-weight: 700;
					color: #1e293b;
					margin-bottom: 16rpx;
				}

				.empty-desc {
					font-size: 28rpx;
					color: #64748b;
					margin-bottom: 48rpx;
					line-height: 1.6;
				}

				.empty-btn {
					display: flex;
					align-items: center;
					gap: 12rpx;
					padding: 24rpx 48rpx;
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					color: #ffffff;
					border-radius: 50rpx;
					font-size: 32rpx;
					border: none;
					box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.35);
					transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
					font-weight: 700;

					&:active {
						transform: scale(0.95);
						box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.25);
					}

					.btn-icon {
						font-size: 32rpx;
					}

					.btn-text {
						font-size: 32rpx;
					}
				}
			}
		}

		/* 加载状态 */
		.loading-overlay {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.5);
			backdrop-filter: blur(10rpx);
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			z-index: 9999;

			.loading-spinner {
				width: 80rpx;
				height: 80rpx;
				border: 6rpx solid rgba(255, 255, 255, 0.3);
				border-top-color: #ffffff;
				border-radius: 50%;
				animation: spin 0.8s linear infinite;
				margin-bottom: 24rpx;
			}

			.loading-text {
				font-size: 28rpx;
				color: #ffffff;
				font-weight: 600;
			}
		}

		/* 悬浮按钮 */
		.fab-button {
			position: fixed;
			right: 32rpx;
			bottom: 120rpx;
			width: 112rpx;
			height: 112rpx;
			background: v-bind('themeStyles.primaryGradient');
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: v-bind('themeStyles.buttonBoxShadow');
			z-index: 100;
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

			&:active {
				transform: scale(0.9) rotate(90deg);
				box-shadow: v-bind('themeStyles.hoverBoxShadow');
			}

			.fab-icon {
				font-size: 56rpx;
				color: #ffffff;
				font-weight: bold;
			}
		}
	}

	/* 动画定义 */
	@keyframes slideDown {
		from {
			opacity: 0;
			transform: translateY(-10rpx) scale(0.95);
		}

		to {
			opacity: 1;
			transform: translateY(0) scale(1);
		}
	}

	@keyframes float {

		0%,
		100% {
			transform: translateY(0);
		}

		50% {
			transform: translateY(-20rpx);
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
</style>